﻿
var fn = {

    toggleBar: function (showID, hideID1, hideID2) {
        $("#" + hideID1).hide();
        $("#" + hideID2).hide();
        $("#" + showID).show();
    },

    toggleBox: function (showID, hideID1, hideID2) {
        $("#" + hideID1).hide();
        $("#" + hideID2).hide();
        $("#" + showID).show();
    },

    addActive: function (addID, removeID1, removeID2) {
        $("#" + removeID1).parent().removeClass("active");
        $("#" + removeID2).parent().removeClass("active");
        $("#" + addID).parent().addClass("active");
    },

    showDropdownMenu: function (showID, hideID) {
        $("#" + showID).on("mouseenter", function () {
            // console.log("mouseenter work");
            $("#" + hideID).show();
        });
        $("#" + showID).on("mouseleave", function () {
            $("#" + hideID).hide();
        });
    },

    popOpen: function () {
        $(".popWindow").show();
    },

    popClose: function () {
        $(".popWindow").hide();
        $(this).hide();
    },

    swiper: function () {
        $(document).ready(function () {
            var mySwiper = new Swiper('.swiper-container', {
                direction: 'horizontal',
                loop: true,
                pagination: '.swiper-pagination',
                nextButton: '.swiper-button-next',
                prevButton: '.swiper-button-prev',
                autoplay: 6000
            })
        })
    },

    formValidate: function () {
        $('#formValidate').validator();
    },

    getAuditcode: function () {
        $("#getAuditcode").on("click", function () {
            $(this).addClass("disabled");
            var t = setTimeout(function () {
                $("#getAuditcode").removeClass("disabled")
                // console.log("work");
            }, 60000);
        });
    }
};


var common = {

    commonAjax: function (options) {

        common.loading(options.loadingCtrl);

        $.ajax({
            type: options.type,
            //contentType: 'application/json',
            url: options.url,
            data: options.data,
            //dataType: 'json',
            success: function (ctx) {

                common.loadComplete(options.loadingCtrl);

                if (common.checkValue(options.alert)) {
                    swal({
                        title: "",
                        text: "提交成功, 2秒后自动关闭。",
                        type: "success",
                        timer: 2000,
                        showConfirmButton: true
                    },
                    function () {
                        swal.close();
                        options.sMethod(ctx);
                    });

                    return;
                }

                options.sMethod(ctx);
            },
            error: function (ctx) {
                debugger;
                common.loadComplete(options.loadingCtrl);

                if (options.fMethod == undefined || options.fMethod == null || options.fMethod == "") {

                    if (common.checkValue(ctx.responseJSON.Message))
                        common.alertMessage(ctx.responseJSON.Message, ctx.status);
                    else
                        common.alertMessage("操作失败,请重新提交。", ctx.status);

                    return;
                }

                options.fMethod(ctx);
            }
        });
    },

    getUrlArgStr: function () {

        var url = location.search;
        var param = [];
        if (url.indexOf("?") != -1) {
            var str = url.substr(1);
            strs = str.split("&");
            for (var i = 0; i < strs.length; i++) {
                param[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
            }
        }

        return param;
    },

    alertMessage: function (msg, status) {

        if (status == undefined)
            status = 0;

        switch (status) {
            //case 400:
            //    alert(data.Message);
            //    break;
            case 400:
                if (common.checkValue(msg))
                    swal({
                        text: msg,
                        title: '',
                        type: "warning",
                        html: true
                    });
                else
                    window.location = "/login.html";
                break;
            case 401:
                window.location = "/login.html";
                break;
            default:
                swal({
                    //text: "操作失败,请重新提交。",
                    text: msg,
                    title: '',
                    type: "warning",
                    html: true
                });
        }
    },

    loading: function (loadingCtrl) {
        if (common.checkValue(loadingCtrl)) {
            //loadingCtrl.append('<div class="message-loading-overlay"><img class="icon-spinner icon-spin" style="width: 212px"></img></div>')
            loadingCtrl.append('<div class="message-loading-overlay"><div class="loding-img" style="width: 212px"></div></div>')
        }
    },

    loadComplete: function (loadingCtrl) {
        if (common.checkValue(loadingCtrl)) {
            loadingCtrl.find('.message-loading-overlay').remove();
        }
    },

    GetSHA: function (val) {

        var shaObj = new jsSHA("SHA-512", "TEXT");
        shaObj.update(val);
        return shaObj.getHash("HEX");
    },

    encrypt: function (str, pwd) {
        if (pwd == null || pwd.length <= 0) {
            pwd = "bingo123";
        }

        var prand = "";
        for (var i = 0; i < pwd.length; i++) {
            prand += pwd.charCodeAt(i).toString();
        }
        var sPos = Math.floor(prand.length / 5);
        var mult = parseInt(prand.charAt(sPos) + prand.charAt(sPos * 2) + prand.charAt(sPos * 3) + prand.charAt(sPos * 4) + prand.charAt(sPos * 5));
        var incr = Math.ceil(pwd.length / 2);
        var modu = Math.pow(2, 31) - 1;
        if (mult < 2) {
            alert("Algorithm cannot find a suitable hash. Please choose a different password. \nPossible considerations are to choose a more complex or longer password.");
            return null;
        }
        var salt = Math.round(Math.random() * 1000000000) % 100000000;
        prand += salt;
        while (prand.length > 10) {
            prand = (parseInt(prand.substring(0, 10)) + parseInt(prand.substring(10, prand.length))).toString();
        }
        prand = (mult * prand + incr) % modu;
        var enc_chr = "";
        var enc_str = "";
        for (var i = 0; i < str.length; i++) {
            enc_chr = parseInt(str.charCodeAt(i) ^ Math.floor((prand / modu) * 255));
            if (enc_chr < 16) {
                enc_str += "0" + enc_chr.toString(16);
            } else enc_str += enc_chr.toString(16);
            prand = (mult * prand + incr) % modu;
        }
        salt = salt.toString(16);
        while (salt.length < 8) salt = "0" + salt;
        enc_str += salt;

        return enc_str;
    },

    decrypt: function (str, pwd) {
        if (str == null || str.length < 8) {
            alert("A salt value could not be extracted from the encrypted message because it's length is too short. The message cannot be decrypted.");
            return;
        }
        if (pwd == null || pwd.length <= 0) {
            pwd = "bingo123";
        }
        var prand = "";
        for (var i = 0; i < pwd.length; i++) {
            prand += pwd.charCodeAt(i).toString();
        }
        var sPos = Math.floor(prand.length / 5);
        var mult = parseInt(prand.charAt(sPos) + prand.charAt(sPos * 2) + prand.charAt(sPos * 3) + prand.charAt(sPos * 4) + prand.charAt(sPos * 5));
        var incr = Math.round(pwd.length / 2);
        var modu = Math.pow(2, 31) - 1;
        var salt = parseInt(str.substring(str.length - 8, str.length), 16);
        str = str.substring(0, str.length - 8);
        prand += salt;
        while (prand.length > 10) {
            prand = (parseInt(prand.substring(0, 10)) + parseInt(prand.substring(10, prand.length))).toString();
        }
        prand = (mult * prand + incr) % modu;
        var enc_chr = "";
        var enc_str = "";
        for (var i = 0; i < str.length; i += 2) {
            enc_chr = parseInt(parseInt(str.substring(i, i + 2), 16) ^ Math.floor((prand / modu) * 255));
            enc_str += String.fromCharCode(enc_chr);
            prand = (mult * prand + incr) % modu;
        }
        return enc_str;
    },

    GetCtrlValues: function (option) {
        var contentID = option.ContentID.toString().indexOf("#") > 0 ? option.ContentID : "#" + option.ContentID;
        var objParent = $(contentID);

        var resultData = {};
        objParent.find("input[type='text'],textarea").each(function () {
            var objThis = $(this);
            resultData[objThis.attr("id")] = objThis.val();
        })
        objParent.find("input[type='password']").each(function () {
            var objThis = $(this);
            var objVal = objThis.val();
            if (objVal != undefined || objVal != "")
                objVal = common.GetSHA(objVal)
            resultData[objThis.attr("id")] = objVal;
        })
        objParent.find("input[type='number']").each(function () {
            var objThis = $(this);
            resultData[objThis.attr("id")] = objThis.val();
        })
        objParent.find("select").each(function () {
            var objThis = $(this);
            resultData[objThis.attr("id")] = objThis.val();
        })
        objParent.find("input[type='radio']").each(function () {
            var objThis = $(this);
            if ($(this).attr("checked") || $(this).prop("checked"))
                resultData[objThis.attr("name")] = objThis.val();
        })
        objParent.find("input[type='checkbox']").each(function () {
            var objThis = $(this);
            if ($(this).attr("checked") || $(this).prop("checked")) {
                var TempArr = resultData[objThis.attr("name")];
                //if (!TempArr) {
                //    TempArr = [];
                //}
                //TempArr.push(objThis.val())
                //resultData[objThis.attr("name")] = TempArr;
                if (TempArr == undefined)
                    TempArr = "";

                TempArr += objThis.val() + "$%#";
                resultData[objThis.attr("name")] = TempArr;
            }

        })

        if (option.returnJson == undefined || !option.returnJson)
            return resultData;
        else
            return JSON.stringify(resultData);

    },

    CreateController: function (option) {

        var app = angular.module('myApp', []);

        app.controller(option.name, function ($http, $scope) {

            $http.get(option.url).success(function (data) {
                debugger;
                switch (option.objType) {
                    case "object":
                        $scope.names = data.ResponseObj;
                        break;
                    case "list":
                        $scope.names = data.ResponseList;
                        break;
                    case "dict":
                        $scope.names = data.ResponseDict;
                        break;
                    case "string":
                        $scope.names = data.ResponseStr;
                        break;
                }

            }).error(function (data, status, headers, config) {
                common.alertMessage(data.Message, status);
            });

        });
    },

    formatDescForDate: function (date) {
        if (date < '1990-01-01')
            return "-";

        return date;
    },

    validateForm: function (form, style) {

        var isValid = true;
        if (!common.checkValue(form) || !common.checkValue(style)) {
            form = $("#formValidate");
            style = $(".help-block");
        }

        form.validator("validate");
        style.each(function () {

            var val = $(this)[0].textContent;
            if (common.checkValue(val)) {
                isValid = false;
            }
        });

        return isValid;
    },

    checkValue: function (val) {
        if (val == "" || val == null || val == undefined)
            return false;

        return true;
    },

    ResetControls: function (parentControlID) {
        $('#' + parentControlID + '' + ' [clearafterclose=true]').each(function () {

            var obj = $(this);
            switch (obj[0].type) {
                case 'file':
                    obj.fileinput('clear');
                    break;
                case 'select-multiple':
                    obj.val("");
                    obj.trigger("chosen:updated");
                    break;
                default:
                    obj.val('');
                    break;
            }
        });
    }
}


